package lvbu.wang.lvbuoperator.utils;

import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.util.Log;

import com.qing.library.utils.DateUtils;

import java.security.MessageDigest;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

import lvbu.wang.lvbuoperator.http.IotHttpHelp;

/**
 * Created by DaiQing.Zha on 2016/6/8 0008.
 * Email:1642674371@qq.com
 * Description:
 */
public class CommonUtil {

    /**
     * 获取apikey
     * @param context
     * @param metaKey
     * @return
     */
    public static String getMetaValue(Context context, String metaKey) {
        Bundle metaData = null;
        String apiKey = null;
        if (context == null || metaKey == null) {
            return null;
        }
        try {
            ApplicationInfo ai = context.getPackageManager()
                    .getApplicationInfo(context.getPackageName(),
                            PackageManager.GET_META_DATA);
            if (null != ai) {
                metaData = ai.metaData;
            }
            if (null != metaData) {
                apiKey = metaData.getString(metaKey);
            }
        } catch (PackageManager.NameNotFoundException e) {

        }
        return apiKey;
    }

    /**
     * MD5加密
     * @param s
     * @return
     */
    public final static String MD5(String s) {
        char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
        try {
            byte[] btInput = s.getBytes();
            // 获得MD5摘要算法的 MessageDigest 对象
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            // 使用指定的字节更新摘要
            mdInst.update(btInput);
            // 获得密文
            byte[] md = mdInst.digest();
            // 把密文转换成十六进制的字符串形式
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String showTemperature(float temperature) {
        DecimalFormat decimalFormat = new DecimalFormat("0.0℃");// 构造方法的字符格式这里如果小数不足1位,会以0补足.
        return decimalFormat.format(Math.abs(temperature));// format 返回的是字符串
    }


    public static String showTripTime(long tripTime) {

        long minute = tripTime / 60;// 秒转为分钟
        minute = Math.abs(minute);
        if (minute <= 60) {
            return "0:" + minute + "";
        } else {
            return (int) Math.floor(minute / 60) + ":" + (minute % 60);
        }
    }


    public static String showTripTimeWithUnit(long tripTime) {

        long minute = tripTime / 60;
        if (minute <= 60) {
            return minute + "分钟";
        } else {
            return (int) Math.floor(minute / 60) + "小时" + (minute % 60) + "分钟";
        }
    }

    public static String showSpeed(double speed) {
        DecimalFormat decimalFormat = new DecimalFormat("0.0");// 构造方法的字符格式这里如果小数不足1位,会以0补足.
        return decimalFormat.format(speed);// format 返回的是字符串
    }

    public static String showTripDist(long tripDist) {
        float km = (float) (tripDist / 1000.0);
        DecimalFormat decimalFormat = new DecimalFormat("0.0");// 构造方法的字符格式这里如果小数不足1位,会以0补足.
        km = Math.abs(km);
        return decimalFormat.format(km);// format 返回的是字符串
    }

    public static String showCalorie(long joule) {

        float calorie = CommonUtil.getCalorie(joule);
        calorie = Math.abs(calorie);
        DecimalFormat decimalFormat;
        if (calorie < 1000) {

            decimalFormat = new DecimalFormat("0.00");    // 构造方法的字符格式这里如果小数不足2位,会以0补足.
            return decimalFormat.format(calorie / 1000); // format 返回的是字符串

        } else {

            decimalFormat = new DecimalFormat("0.0");     // 构造方法的字符格式这里如果小数不足1位,会以0补足.
            return decimalFormat.format(calorie / 1000); // format 返回的是字符串
        }
    }

    /**
     * 获取卡路里
     *
     * @param joule
     *            焦耳
     * @return
     */
    public static float getCalorie(long joule) {
        return joule * 0.2389f;
    }

    public static float getAverageSpeed(long tripDist, long tripTime) {
        if (tripTime == 0) {
            return 0;
        }
        return (float) (Math.abs((tripDist / 1000.0) / (tripTime / 3600.0)));
    }

    /**
     * 获取用户头像
     * @param fileName
     * @return
     */
    public static String Get_Uri_Pic_UserFace(String fileName) {
        return IotHttpHelp.getWebsite_cdn() + "pic/userface/" + fileName + "";// 从CDN获取
    }
    /**
     * 获取车辆头像
     * @param fileName
     * @return
     */
    public static String Get_Uri_Pic_BikePhoto(String fileName) {
        return IotHttpHelp.getWebsite_cdn() + "pic/bikephoto/" + fileName + "";// 从CDN获取
    }

    public static String Get_Uri_App_Version(String id) {
        return IotHttpHelp.getWebsite_cdn() + "app/version/" + id + ".apk";// 从CDN获取
    }

    public static String Date2String(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(date);
    }

    public static String Date2Week(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int dayIndex = calendar.get(Calendar.DAY_OF_WEEK);
        if (dayIndex == 1) {// 星期天
            dayIndex = 7;
        } else {
            dayIndex = dayIndex - 1;
        }

        switch (dayIndex) {
            case 1:
                return "星期一";
            case 2:
                return "星期二";
            case 3:
                return "星期三";
            case 4:
                return "星期四";
            case 5:
                return "星期五";
            case 6:
                return "星期六";
            case 7:
                return "星期天";
            default:
                break;
        }
        return "";
    }

    public static Date String2Date(String dateString) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            dateString = dateString.replace("T", " ");
            if (dateString.length() > 19) {
                dateString = dateString.substring(0, 19);
            }
            return sdf.parse(dateString);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            // CrashReport.postCatchedException(e);
        }
        return new Date();
    }
    /**
     * 判断用户是否安装第三方软件
     * @param context
     * @param packName
     * @return
     */
     public static boolean isAviliable(Context context,String packName){

        PackageManager packageManager = context.getPackageManager();
        List<PackageInfo> packageInfos = packageManager.getInstalledPackages(0);
        List<String> packNames = new ArrayList<>();
        if (packageInfos != null){

            for (int i = 0; i < packageInfos.size(); i++){

                packNames.add(packageInfos.get(i).packageName);
            }
        }
        return packNames.contains(packName);
    }


    /**
     * 获取签名
     * @param context
     * @return
     */
    public static String getSign(Context context) {

        DateFormat dateFormatter=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        TimeZone pst = TimeZone.getTimeZone("Etc/GMT+0");

        Date curDate = new Date();
        dateFormatter.setTimeZone(pst);
        String str=dateFormatter.format(curDate);//这就是我们想要获取的值
        long longTime = DateUtils.formatStr(str, DateUtils.TYPE_01);
        String strDate = DateUtils.formatDate(longTime,DateUtils.TYPE_09);
        return strDate + MD5(strDate + "lvbu365@1234567890").toLowerCase();
    }

    /**
     * 转换蓝牙地址格式
     * 将不带冒号的蓝牙地址转换为带冒号的
     * @param address
     * @return
     */
    @NonNull
    public static String convertBluetoothAddress(@NonNull String address){
        StringBuffer stringBuffer = new StringBuffer();
        if (address.length() >= 2){
            for (int i = 0; i < address.length() - 1; i ++){
                if (i == 0) {
                    stringBuffer = stringBuffer.append(address.substring(i,i + 2));
                }else{
                    stringBuffer = stringBuffer.append(":" + address.substring(i,i + 2));
                }
                i++;
            }
        }
        Log.e("main_BLE","stringBuffer.toString() " + stringBuffer.toString().toUpperCase());
        return stringBuffer.toString().toUpperCase();
    }

}
